import webapi
import md5, time, base64, string, cPickle, base64, re
from configuration import Database

class session:
	def __init__(self,config):
		# Set the sessionid to cookie
		self.id = ""
		self.values = {}
		self.config = config
		
		## Gather data if there
		cookies	= webapi.cookies()
		input	= webapi.input()
		if cookies.has_key("session_id") and cookies["session_id"] != "" and cookies["session_id"] != None:
			self.id = cookies["session_id"]
		else:
			if input.has_key("session"):
				self.id = input.session
			else:
				self.makeSessionId("test")
			
	def initDB(self):
		## DB setup
		self.db = Database()
		self.db.type = self.config.db.type
		self.db.version = self.config.db.version
		if self.db.type == "SQLite":
			self.db.filename = self.config.db.filename
	def saveSession(self):
		self.initDB()
		if self.db.type == "SQLite":
			## DB connection
			self.db.Connect()
			self.db.Query("SELECT id FROM sessions WHERE id='%s'"%self.id)
			result = self.db.cursor.fetchall()
			self.db.Close()
			
			self.initDB()
			self.db.Connect()
			if result:
				self.db.Query("UPDATE sessions SET data='%s' WHERE id='%s'"%(base64.b64encode(cPickle.dumps(self.values)),self.id))
			else:
				self.db.Query("INSERT INTO sessions (id,data,created) VALUES ('%s','%s','%s')"%(self.id,base64.b64encode(cPickle.dumps(self.values)),str(time.time())))
			self.db.Close()
			
	def deleteSession(self):
		self.initDB()
		if self.db.type == "SQLite":
			## DB connection
			self.db.Connect()
			self.db.Query("DELETE FROM sessions WHERE id='%s'"%self.id)
			self.db.Close()
		webapi.setcookie("session_id", self.id, 0)
	
	def linkEncoder(self,tmpl):
		""" Converts local links to include session id """
		if self.values.has_key("session_url") and self.values["session_url"]:
			for link in re.findall("href=\"([^\"]+)\"", tmpl):
				if link[:7] != "http://" and link[0] != "#":
					sessionLink = ""
					if link.split("/")[-1].find("?") > -1:
						sessionLink = link+"&session="+self.id
					else:
						sessionLink = link+"?session="+self.id
					tmpl = tmpl.replace(link,sessionLink)
			for link in re.findall("action=\"([^\"]+)\"", tmpl):
				if link[:7] != "http://" and link[0] != "#":
					sessionLink = ""
					if link.split("/")[-1].find("?") > -1:
						sessionLink = link+"&session="+self.id
					else:
						sessionLink = link+"?session="+self.id
					tmpl = tmpl.replace(link,sessionLink)
		return tmpl
	
	def loadSession(self):
		self.initDB()
		if self.db.type == "SQLite":
			## DB connection
			self.db.Connect()
			self.db.Query("SELECT data FROM sessions WHERE id='%s'"%self.id)
			self.db.Fetch(all=False)
			
			if self.db.result and self.db.result[0] != None:
				self.values = cPickle.loads(base64.b64decode(self.db.result[0]["data"]))
			self.db.Close()
	def makeSessionId(self,st):
		import md5, time, base64, string
		m = md5.new()
		m.update('this is a test of the emergency broadcasting system')
		m.update(str(time.time()))
		m.update(str(st))
		self.id = base64.encodestring(m.digest())[:-3]
		self.id = self.id.replace("+","_")
		self.id = self.id.replace("\\","_")
		self.id = self.id.replace("/","_")
		self.id = self.id.replace("$","_")
		self.id = self.id.replace(" ","_")
		self.id = self.id.replace("@","_")
		webapi.setcookie("session_id", self.id, (60*60)) #Session for 1 hour 60sec*60mins